package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class CustomerUserInterceptor implements HandlerInterceptor {
    @Autowired
    JwtProperties jwtProperties;

    /**
     * 小程序Token校验
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("服务端拦截器: {}",request.getRequestURI());
        // 非映射方法放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取token
        String token = request.getHeader(jwtProperties.getTokenName());

        // 判断token是否为空
        if (StringUtils.isEmpty(token)) {
            // token为空
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        // 解析token
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
        } catch (Exception e) {
            // 解析token失败
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        // 从载荷中获取userId
        Long userId = Long.valueOf(claims.get(Constants.JWT_USERID).toString());

        // 判断userId是否为空
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        // 往当前线程设置userId
        UserThreadLocal.set(userId);
        // 放行
        return true;
    }

    /**
     * 释放资源
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
